Hello!
This is currently my biggest problem with the chatserver. I need to find out if a client is still connected so I can free up the slot and close the connection when a client leaves.
Every connected client goes into a loop, constantly writing new stuff to the socket (the browser) which is the chat stream. Unfortunatly the "write" function I use to do this never returns -1, even if the browser already closed the connection so I have no way to find ouy if it's still there and receiving.
The code looks like this:
Code:
while(connected) {
// check the buffer for new text to send
if (strlen(chatter[myid].buffer) > 0) {
sprintf(sendbuf, "%s", chatter[myid].buffer);
sprintf(chatter[myid].buffer, "");
if(write(sock, sendbuf, strlen(sendbuf)) == -1)
connected = 0; // never ever happens
}
}
sleep(1);
}
So out of couriousity I tried what happens when I read() from the browser just as a test if it's still there:
Code:
while(connected) {
// read something from the browser, just as a test...
if(read(sock, NULL, 1) == -1)
fprintf(stderr, "party! we are disconnected\n");
else
fprintf(stderr, "still connected :/\n");
sleep(1);
}
This shows me that it _could_ work, because what happens is, that the function stops there at the read, waiting for the browser to actually send 1 char. Of course it doesn't. But when I close the connection from the browser now, it returns -1 and detects that it's disconnected! It doesn't work when I try to read 0 chars.
There _has_ to be a way to find out if the browser is still connected. :/ Please help cause I'm lost.